package com.fivebrms.hibernate.entity.business;

import java.lang.reflect.InvocationTargetException;
import java.sql.Timestamp;
import java.util.Collection;
import java.util.GregorianCalendar;
import java.util.Iterator;

import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.fivebrms.forms.w9.forms.RemoteLoginCredentials;
import com.fivebrms.hibernate.entity.dao.LoginDaoHibernate;
import com.fivebrms.hibernate.entity.model.LoginForm;

public class LoginService
{
	final Logger	log	= LoggerFactory.getLogger(LoginService.class);

	public RemoteLoginCredentials login(RemoteLoginCredentials loginCredentials)
	{
		log.info("login..ok successfully called the logger.. " + loginCredentials);

		ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(flex.messaging.FlexContext
		        .getServletConfig().getServletContext());

		log.info("form created..2..");

		String loginSpringBean = "loginCredentialsDao";

		LoginDaoHibernate loginDao = (LoginDaoHibernate) appContext.getBean(loginSpringBean);

		LoginForm loginForm = new LoginForm();
		try
		{
			BeanUtils.setProperty(loginForm, "login", loginCredentials.getLogin() );
			BeanUtils.setProperty(loginForm, "password", loginCredentials.getPassword() );
			BeanUtils.setProperty(loginForm, "dateCreated", GregorianCalendar.getInstance().getTimeInMillis() );
			BeanUtils.setProperty(loginForm, "dateLastLogin", GregorianCalendar.getInstance().getTimeInMillis() );
		}
		catch (IllegalAccessException iae)
		{
			log.error("an error IllegalAccessException...", iae);
		}
		catch (InvocationTargetException ite)
		{
			log.error("an error occurred...", ite);
		}
		//
		// place the object into the database
		//
		loginDao.createLoginForm(loginForm);

		//
		// for now all login's are successful
		//
		loginCredentials.setLoginSuccessful(true);
		
		log.info("login..finished loginCredentialsDao successfully.. ");

		log.info("login looking..size-->" + loginDao.findAll().size());

		return loginCredentials;
	}


}
